<template>
  <el-dialog
    ref='dialog'
    :visible='visible'
    @close='handleClose'
    :before-close='beforeClose'
    title='Result'
    width='800px'
    height='600px'
  >
    <div style='margin: 0 10px 0 10px;'>
      <div v-if='msgTitle' style='margin-bottom: 5px;'>
        <el-alert
          :closable='false'
          :title='msgTitle'
          :type='msgType'
          show-icon
          :description='alertMsg'>
        </el-alert>
      </div>
      <div>
        <el-table
          :show-overflow-tooltip='true'
          style='margin-bottom: 20px'
          v-loading='listLoading'
          :data='tableData'
        >
          <el-table-column label='SN' prop='devSn' align='center' />
          <!--          <el-table-column :label="$t('device.tid')" prop='devTid' align='center' />-->
          <!--          <el-table-column :label="$t('batch.status')" align='center'>-->
          <!--            <template v-slot="{row}">-->
          <!--              <el-tag-->
          <!--                :type="row.status == 3 ? 'danger' : (row.status == 2 ? 'success' : '')"-->
          <!--              >-->
          <!--                {{ statusFilter(row.status) }}-->
          <!--              </el-tag>-->
          <!--            </template>-->
          <!--          </el-table-column>-->
                    <el-table-column :label="$t('batch.message.push_result_message')" prop='code' align='center'>
                      <template v-slot="{row}">
                        <span>{{ messageFilter(row.code) }}</span>
                      </template>
                    </el-table-column>
        </el-table>
      </div>
    </div>
    <template #footer>
    <span class='dialog-footer'>
<!--      <el-button v-if="(details.successCounts > 0) && details.errorCounts > 0" size="small" type="primary" :loading="importLoading" @click="importVerifySuccessDev">{{ $t('common.import') }}</el-button>-->
      <el-button v-if='tableData.length > 0' size='small' type='primary'
                 @click='exportFile'>{{ $t('common.downloadBtn')
        }}</el-button>
      <el-button size='small' @click='cancel'>{{ $t('common.close') }}</el-button>
    </span>
  </template>
  </el-dialog>
</template>

<script>
import XLSX from 'xlsx'
import { addBatchDeviceList, delBatchLegalDevices } from '@/api/batch'

export default {
  props: {
    visible: Boolean
  },
  data() {
    return {
      msgTitle: '',
      msgType: '',
      alertMsg: '',
      tableData: [],
      listLoading: false,
      hasDownload: false,
      details: {},
      operationType: 'add',
      batchId: 1
    }
  },
  methods: {
    statusFilter(status) {
      const statusMap = {
        0: this.$t('common.fail'),
        1: this.$t('common.success'),
        2: this.$t('batch.message.validation_succeed'),
        3: this.$t('batch.message.validation_fail'),
        4: this.$t('batch.message.transferring')
      }
      return statusMap[status]
    },
    messageFilter(status) {
      const messageMap = {
        'NOT_EXIST': this.$t('batch.not_exist_tip'),
        'MODEL_NOT_MATCH': this.$t('batch.model_not_match'),
        'OPERATOR_NO_RELEASE_THIS_VERSION': this.$t('batch.operator_no_release_this_version')
      }
      return messageMap[status]
    },
    cancel() {
      this.$refs.dialog.handleClose()
    },
    handleClose() {
      this.msgTitle = ''
      this.msgType = ''
      this.alertMsg = ''
      this.hasDownload = false
      this.$emit('update:model-value', false)
      this.$emit('refreshDataList')
    },
    init(res, operationType, batchId) {
      this.details = res
      this.tableData = res
      this.operationType = operationType
      this.batchId = batchId

      this.msgTitle = this.$t('batch.message.msg_not_push_title', {
        count: res.length
      })
      this.msgType = 'success'
      this.alertMsg = this.$t('batch.message.alert_msg_push_success')
      this.hasDownload = false
    },
    beforeClose(done) {
      if (this.hasDownload === false) {
        this.$confirm(this.$t('batch.message.not_download_not_push_list_tip'))
          .then(_ => {
            done()
          })
          .catch(_ => {
          })
      } else {
        done()
      }
    },
    importVerifySuccessDev() {
      this.hasDownload = true
      var operation = this.operationType === 'add' ? this.$t('batch.operation_add') : this.$t('batch.operation_delete')

      this.$confirm(this.$t('batch.only_import_success_tip', { operationType: operation }),
        this.$t('common.tips'),
        {
          confirmButtonText: this.$t('page.confirm'),
          cancelButtonText: this.$t('page.cancel'),
          type: 'warning'
        }).then(
        () => {
          this.importLoading = true
          var data = []
          for (var item of this.tableData) {
            // 验证通过的数据
            if (item.status === 2) {
              data.push(item)
            }
          }
          if (this.operationType === 'add') {
            addBatchDeviceList(this.batchId, { devSnList: data }).then((res) => {
              this.handleClose()
              this.$message.success(this.$t('page.add_success'))
            }).catch((e) => {
              this.$confirmError(e)
            }).finally(() => {
              this.importLoading = false
            })
          } else if (this.operationType === 'delete') {
            delBatchLegalDevices({ batchId: this.batchId, devSnList: data }).then((res) => {
              this.handleClose()
              this.$message.success(this.$t('page.delete_success'))
            }).catch((e) => {
              this.$confirmError(e)
            }).finally(() => {
              this.importLoading = false
            })
          }
        })
    },
    format(time, format) {
      var t = new Date(time)
      var tf = function(i) {
        return (i < 10 ? '0' : '') + i
      }
      return format.replace(/yyyy|MM|dd|HH|mm|ss/g, function(a) {
        switch (a) {
          case 'yyyy':
            return tf(t.getFullYear())
          case 'MM':
            return tf(t.getMonth() + 1)
          case 'mm':
            return tf(t.getMinutes())
          case 'dd':
            return tf(t.getDate())
          case 'HH':
            return tf(t.getHours())
          case 'ss':
            return tf(t.getSeconds())
        }
      })
    },
    getNowTime() {
      // var timezone = 8; //目标时区时间，东八区
      var timezone = 0 - new Date().getTimezoneOffset() / 60
      console.log(timezone)
      var offset_GMT = new Date().getTimezoneOffset() // 本地时间和格林威治的时间差，单位为分钟
      var nowDate = new Date().getTime() // 本地时间距 1970 年 1 月 1 日午夜（GMT 时间）之间的毫秒数
      var targetDate = new Date(
        nowDate + offset_GMT * 60 * 1000 + timezone * 60 * 60 * 1000
      )
      return this.format(targetDate, 'YYYYMMDD-HHmmss')
    },
    exportFile() {
      if (this.tableData.length < 0) {
        return
      }
      let data = this.tableData.slice()
      let arr = new Array()
      arr[0] = ['devSn','message']
      for (var i = 0; i < data.length; i++) {
        var val = data[i]
        arr[i + 1] = new Array()
        arr[i + 1][0] = val['devSn']
        arr[i + 1][1] = this.messageFilter(val['code'])
      }
      const ws_name = 'Sheet1',
        wb = XLSX.utils.book_new(),
        ws = XLSX.utils.aoa_to_sheet(arr)
      XLSX.utils.book_append_sheet(wb, ws, ws_name)
      XLSX.writeFile(wb, 'Group-devices-not-push-' + this.getNowTime() + '.xlsx')
      this.hasDownload = true
    }
  }
}
</script>

<style lang='scss' scoped>
.header {
  height: 86px;
}
</style>
